﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Configuration;
using System.Web;
using System.Web.Configuration;

namespace XUtility
{
    public static class WebConfig
    {
        #region 读取 Web.config
        /// <summary>
        /// 读取 Web.config 指定键的值 [String类型]
        /// </summary>
        /// <param name="key">键</param>
        public static String GetAppSetting(String key)
        {
            try
            {
                String str = ConfigurationManager.AppSettings[key];
                if (!str.HasValue())
                    str = String.Empty;
                return str;
            }
            catch
            {
                return String.Empty;
            }
        }
        /// <summary>
        /// 读取 Web.config 指定键的值 [Int32 类型]
        /// </summary>
        /// <param name="key">键</param>
        public static Int32 GetAppSettingsToInt32(String key)
        {

            String value = GetAppSetting(key);
            Int32 result = 0;
            Int32.TryParse(value, out result);

            return result;
        }

        /// <summary>
        /// 获取数据库连接串
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static String GetConnectionString(String key)
        {
            try
            {
                String str = ConfigurationManager.ConnectionStrings[key].ToString();
                if (!str.HasValue())
                    str = String.Empty;
                return str;
            }
            catch
            {
                return String.Empty;
            }
        }
        #endregion

        #region 保存 Web.config
        /// <summary>
        /// 修改或新增appSetting
        /// </summary>
        /// <param name="path">Web.config路径</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        [Obsolete("已过时，请使用SetAppSetting")]
        public static void SetConfig(String path, String key, String value)
        {
            //获取xml对象
            XmlDocument document = new XmlDocument();
            //获取 根web.config 路径
            document.Load(path);
            //获取configuration/appSettings节点参数数组
            XmlNodeList nodes = document.SelectSingleNode("configuration/appSettings").ChildNodes;
            //修改 根web.config 参数值
            foreach (XmlNode node in nodes)
            {
                XmlElement element = node as XmlElement;
                if (element != null)
                {
                    String configKey = element.Attributes.GetNamedItem("key").Value;
                    if (configKey != null)
                    {
                        if (configKey == key)
                        {
                            element.Attributes.GetNamedItem("value").Value = value;
                        }
                    }
                }
            }
            //保存修改
            document.Save(path);
            //休眠0.5秒
            System.Threading.Thread.Sleep(500);
        }

        /// <summary>
        /// 修改或新增appSetting
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void SetAppSetting(string key, string value)
        {
            var config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            try
            {
                AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
                if (appSetting.Settings[key] == null)//如果不存在此节点,则添加  
                {
                    appSetting.Settings.Add(key, value);
                }
                else//如果存在此节点,则修改  
                {
                    appSetting.Settings[key].Value = value;
                }
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                config = null;
            }

        }

        /// <summary>
        /// 设置数据库连接字符串节点,如果不存在此节点,则会添加此节点及对应的值,存在则修改  
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="connectionString">值</param>
        /// <param name="providerName">数据库连接方式</param>
        public static void SetConnectionString(String key, String connectionString, String providerName = "System.Data.SqlClient")
        {
            var config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            try
            {
                var connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings");
                if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此节点,则添加  
                {
                    var connectionStringSettings = new ConnectionStringSettings(key, connectionString, providerName);
                    connectionSetting.ConnectionStrings.Add(connectionStringSettings);
                }
                else//如果存在此节点,则修改  
                {
                    connectionSetting.ConnectionStrings[key].ConnectionString = connectionString;
                }
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("connectionStrings");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                config = null;
            }

        }
        #endregion
    }
}
